import { createRouter, createWebHistory } from 'vue-router'
import loginView from '@/views/login/index.vue'

import regView from '@/views/reg/index.vue'
import homeView from '@/views/home/home.vue'

import indexView from '@/views/home/children/index.vue'
import claView from '@/views/home/children/cla.vue'
import cartView from '@/views/home/children/cart.vue'
import myView from '@/views/home/children/my.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: loginView,
    },
    {
      path: '/reg',
      name: 'reg',
      component: regView,
    },
    {
      path: '/',
      redirect: '/reg'
    },
    {
      path: '/home',
      name: 'home',
      component: homeView,
      children: [
        {
          path: 'index',
          name: 'index',
          component: indexView,
        },
        {
          path: 'cla',
          name: 'cla',
          component: claView,
        },
        {
          path: 'cart',
          name: 'cart',
          component: cartView,
        },
        {
          path: 'my',
          name: 'my',
          component: myView,
        },
      ]
    },

  ],
})
// 导航守卫
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('toekn')
  if (!token) {
    if (to.fullPath == '/home/cart' || to.fullPath == '/home/my') {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})
export default router
